/**
 * 功能：我的钱包
 * 
 */
// react基础组件
import React from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'
import { Link,hashHistory } from 'react-router';
// 自定义封装组件
import {DanluJsBridge,filter,logger,http} from 'common/index'
import {Alert,PullLoad,Header,BtnGroup,LoadMore} from 'components/index'
import {Remainder,BankCard,Caption,BillList,UnsupportWallet} from './subpage/index'
// redux
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as walletInfoActionsFromOtherFile from '../../store/actions/walletinfo' 
import axios from 'axios'

class MyWallet extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
        this.state = {
            showAlert : false,
            supportFlag :  false, 
            unsuppotWallet : this.props.unsuppotWallet || '' ,
            isLoadingMore : false,
            userInfo : {  // 用户信息
                userid : '',
                companyId : ''
            },
            companyAccount : "", //对公账户
            personAccount :"",//对私账户  
            accountStatus : '',
            billList : [],//账单列表
            accType : '',
            billBtnList :[],
            billPageIndex : 0,
            billPageSize : 20,
            billTotal : 0,
            billHasMore : true

        }
    }
    componentWillMount (){
        let _this = this;
        _this.setState({
            unsuppotWallet : this.props.walletinfo.supportFlag 
        })
        DanluJsBridge.callHandler("setBackBtnColor", {
              color: '#ffffffff'
          });
        DanluJsBridge.callHandler('setTitleBarColor', {
            color: ['#fffc7646','#fff5a466']
        }, function() {
            alert(123)
        })
        //设置导航菜单
        DanluJsBridge.callHandler('setOptionMenu', {menus: [{
            title: '',
            color: '#ffffffff'
        }]})

        DanluJsBridge.callHandler('setTitle', {
            title: '我的钱包',
            color: '#ffffffff',
        })
        
        // 添加事件监听
        DanluJsBridge.registerHandler('handlerNativeMessage',function(e){
            if (e.event == 'optionMenuClickEvent') {
            }
        })

        DanluJsBridge.callHandler('getSessionData', {
          keys: ['user']
        }, function(result) {
            var result = Object.assign({},result)
            //开始获取基本信息
            var userId = result.userId 
            var companyId = result.companyId 
            _this.setState({
                userInfo : {
                    userId : userId,
                    companyId :companyId
                }
            },() =>{
                //开始网络请求
                _this.getPayAccountInfo(); //获取开户信息
                
            })   

            _this.props.walletinfoActions.walletInfoUpdate({
                user : result
            }) 
        });
    }

    componentDidMount() {
        // DanluJsBridge.callHandler('hideLoading');
        // 初始化下拉刷新
    }
    

    // 关闭弹窗
    closeAlert (){
        this.setState({
            showAlert : false
        })
    }
    //展示钱包余额详情
    openAlert (){
        this.setState({
            showAlert : true
        })

    }
    //获取用户真实姓名
    getLawyerNameAndId(){
        var _this = this;
        var reqData = this.state.userInfo
        http.get('/dlpcweb/dlpc/pc/V1/wallet/getLawyerNameAndId',reqData).then( data => {
            if (data.name) {
                var user = Object.assign({},this.props.walletinfo.user,data) 
                this.props.walletinfoActions.walletInfoUpdate({
                    user : user
                })  
            }
        })
    }
    //查询开户信息
    getPayAccountInfo (){
        var _this = this;
        var reqData = {
            "userId":this.state.userInfo.companyId, //这里userId需要传companyId ,遗留问题
            "payMechanism":"04"
        }
        http.post('/dlpcweb/dlpc/pc/V1/accountInfo/getPayAccountInfo',reqData).then( (data) => {
            if (data && data.length){
                // 确认开户，进行其他请求
                _this.getBalance();
                _this.getBindCards();
                _this.getSupportBindBankList();
                _this.havePassword();
                _this.getLawyerNameAndId()
                // --------------------------
                var payAccountInfo = {}
                var accountStatus = ''
                var billBtnList = []
                var accType = ''
                data.map ( acc => { 
                    if(acc.accountType == '0') {
                        payAccountInfo.companyAccount = acc
                        accountStatus = acc.status
                    }else{
                        payAccountInfo.personAccount = acc
                        accountStatus = acc.status
                    }
                })
                if(payAccountInfo.personAccount){
                    billBtnList.unshift({
                        title : "个人账单",
                        value : '209'
                    })
                    accType = '209'
                }
                if (payAccountInfo.companyAccount) {
                    billBtnList.unshift({
                        title : "公司账单",
                        value : '208'
                    })
                    accType = '208'
                }
                this.tradeQuery(accType).then().catch( () => {
                    this.setState({
                        billHasMore : false
                    })
                });

                this.setState({
                    unsuppotWallet : false,
                    supportFlag : true,
                    companyAccount : payAccountInfo.companyAccount,
                    personAccount  : payAccountInfo.personAccount,
                    accountStatus :accountStatus,
                    billBtnList : billBtnList,
                    accType : accType
                })
                this.props.walletinfoActions.walletInfoUpdate({
                    payAccountInfo : payAccountInfo,
                    accountStatus :accountStatus,
                })                   
            }else{
                this.setState({
                    unsuppotWallet : true,
                    supportFlag : true
                })
                  
            }
            this.props.walletinfoActions.walletInfoUpdate({
                supportFlag : true
            }) 
        })
    }
    //检验是否设置了丹露支付密码
    havePassword (){
        var reqData = {
            "userId": this.state.userInfo.userId,
        }
        http.get('/dlpcweb/dlpc/pc/V1/paymentPassword/havePassword',reqData).then((data) =>{
            this.props.walletinfoActions.walletInfoUpdate({
                havePassword : data
            })
            
        })
    }
    //查询余额
    getBalance (){
        var _this = this;
        return new Promise(function(resolve,reject){
           var reqData = {
            "userId": _this.state.userInfo.userId,
            "companyId": _this.state.userInfo.companyId
        }
        http.post('/dlpcweb/dlpc/pc/V1/wallet/getBalance',reqData).then((data) =>{
            var balanceDetail = data.balanceDetail || []
            balanceDetail = balanceDetail.sort((a,b) =>{ return a.acc_type - b.acc_type })
            _this.props.walletinfoActions.walletInfoUpdate({
                balanceDetail : balanceDetail,
                withDrawFee : data.withDrawFee
            })
            resolve();
        }).catch(function(e){
            resolve();
        })           
    })


    }

    //查询账户账单流水
    tradeQuery (accType){
        var _this = this;
        //获取当前日期
        var time  = new Date();
        var year = time.getFullYear().toString()
        var month = time.getMonth()+1 < 10 ? "0"+(time.getMonth()+1).toString() : (time.getMonth()+1).toString()
        var day = time.getDate()+1 < 10 ? "0"+(time.getDate()+1).toString() : (time.getDate()+1).toString()
        var today = year + month + day
        var pageIndex = this.state.billPageIndex +1 
        var pageSize = this.state.billPageSize 
        var reqData = {
            "userId":this.state.userInfo.userId, 
            "companyId":this.state.userInfo.companyId, 
            "accType": accType,
            "startDate":"20180301",
            "endDate": today,
            "pageIndex":pageIndex.toString(),
            "pageSize":pageSize.toString()

        }
        return new Promise(function(resolve,reject){
            http.post('/dlpcweb/dlpc/pc/V1/wallet/tradeQuery',reqData,{custom:true}).then( (data) => {
                if (data.status == 0){
                    var billList = _this.state.billList
                    billList = billList.concat(data.data_list)
                    var billPageIndex = _this.state.billPageIndex
                    
                    //判断是否含有更多
                    if (data.index * data.size <= data.total) {
                        _this.setState({
                            billList : billList,
                            billPageIndex : ++billPageIndex,
                            billHasMore : true,
                            billTotal : data.total
                        }) 
                        resolve(true)
                    }else{
                        var hasMore = !billList.length
                        _this.setState({
                            billList : billList,
                            billHasMore : hasMore,
                            billTotal : data.total
                        }) 
                        reject(false)
                    }
                    
                }else{
                    DanluJsBridge.callHandler('alert', {
                        title: '提示',
                        message: "获取账单失败",
                        button: '我知道了'
                    })
                    reject(false)
                }

            })          
        })
        
    }
    //查询绑定的银行卡
    getBindCards (){
        var reqData = {
            "userId": this.state.userInfo.userId,
            "companyId": this.state.userInfo.companyId
        }
        http.post('/dlpcweb/dlpc/pc/V1/wallet/getBindCardList',reqData).then((data) =>{
            var bindCards = data || []
            this.props.walletinfoActions.walletInfoUpdate({
                bindCards : bindCards
            })
            
        })
    }

    //获取支持银行卡列表
    getSupportBindBankList (){
        var _this = this;
        http.post('/dlpcweb/dlpc/pc/V1/wallet/bindBankList',{}).then(data => {
            //银行卡图标与URL封装
            var bankEnume = {}
            if (data && data.length) {
                data.map( item =>{
                    bankEnume[item.bankId] = item.bankIconUrl
                })
            }

            // 更新到store
            this.props.walletinfoActions.walletInfoUpdate({
                supportCards : data, //支持的银行卡列表
                bankEnume : bankEnume    //银行卡名称与图标间的关系
            })
        })
        
    }

    //下拉刷新
    handRefreshing(callback){
        var queryArr = []
        this.setState({
            billPageIndex : 0,
            billList : [],
            billHasMore : true
        },function(){
            queryArr.push(this.getPayAccountInfo());
            queryArr.push(this.getBindCards());
            queryArr.push(this.getBalance())
            // queryArr.push(this.tradeQuery(this.state.accType))
            Promise.all(queryArr).then(() =>{
                callback();
            },() =>{
                callback();
            })
            
        })
    }
    // 上拉加载
    handLoadMore (callback){
        if (!this.state.billHasMore) {
            setTimeout(function(){
                callback(true)
            },500)
            
        }else{
            this.tradeQuery(this.state.accType).then(function(){
                console.log('hasMore:true')
                callback(true)
            },function(){
                console.log('hasMore:false')
                callback(false)
            })
        }
    }

    //
    accTypeChange(accType){
        this.setState({
            accType : accType,
            billPageIndex : 0,
            billList : [],
            billHasMore : true
        },function(){
         this.tradeQuery(accType).then(function(){

         },function(){

         }); 
     })
        
    }

    goBmikece (acc_type){
        if (this.state.accountStatus == '0') {
            //跳转到银行卡列表页
            hashHistory.push({
                pathname:'/bmikece',
                state:{
                    acc_type:acc_type
                }
            });
        }
        
    }
    render() {

        const balanceDetail = this.props.walletinfo.balanceDetail || []
        const Cards = this.props.walletinfo.bindCards || []
        const bindCards = Cards.slice(0,2);
        return (

            <div className="myWallet">
            {
                this.state.supportFlag != true ? '':  
                    this.state.unsuppotWallet ? <UnsupportWallet></UnsupportWallet> : 
                    
                    <div className="container">
                    <Header title="我的钱包" className="wallet-hader"> </Header>
                    
                    { this.state.showAlert===true ?   
                        <Alert close={this.closeAlert.bind(this)}>
                            <div className="alert-content account-explain">
                                {
                                    this.state.companyAccount ? 
                                    <div className="account-info">
                                        <span>公司账户：</span>
                                        <p>开发票订单的交易款项将会进入公司账户余额。</p>
                                    </div> : ''
                                }
                                {
                                    this.state.personAccount ?
                                    <div className="account-info">
                                        <span>个人账户：</span>
                                        <p>不开发票订单的交易款项会进入个人账户余额。</p>
                                    </div> : ''
                                }
                                <div className="account-last">
                                    <span>余额数值：</span>
                                    <p>买家通过POS刷卡、微信支付宝扫码、丹露钱包支付的交易资金会计入余额</p>
                                </div>
                            </div>
                            <div className="close-btn-extend" >
                                <i onClick={this.closeAlert.bind(this)} className="iconfont icon-close1"></i>
                            </div>
                        </Alert> : ''}
                    {/*<PullLoad headerClass="wallet-hader" handRefreshing={this.handRefreshing.bind(this)} handLoadMore={this.handLoadMore.bind(this)} hasMore={this.state.billHasMore}>*/}
                    <div  >
                    
                    <div className="wallet-hader ">
                    <div className="padding5 wallet-account content">
                    钱包余额 <i className="iconfont icon-help" onClick={this.openAlert.bind(this)}></i>
                    </div>
                    <div >
                    {
                        balanceDetail.map((item,index) =>{
                            return  <div className="wallet-account account content" key={index} onClick={this.goBmikece.bind(this,item.acc_type)}>
                            <div className="inline-block padding5" >
                            {
                                item.acc_type == 208 ? <img src={require('static/image/wallet-company.png')} alt="" /> 
                                : <img src={require('static/image/wallet-person.png')} alt="" /> 
                            }
                            </div>
                            <div className="inline-block sum padding5">
                            <div className="font12">
                            {
                                item.acc_type == 208 ? <span >公司账户</span> 
                                : <span >个人账户</span>
                            }
                            </div>
                            <div>
                            <strong className="font24">{filter.toMoneyFormat(item.balance)}</strong>
                            </div>
                            </div>
                            {
                                this.state.accountStatus == 0 ? <div className="inline-block  float-right" style={{lineHeight:'0.7rem',color:'white'}}>
                                <i className="iconfont icon-right font24" style={{color:'white'}}/>
                                </div> : ''
                            }
                            
                            </div>
                        })
                    }
                    </div>
                    </div>
                    {/* 近期交易*/}    
                    {
                        <Caption title="我的银行卡" >
                        {
                            this.state.personAccount && this.state.accountStatus==0 ? <Link to="bankCardList" >查看更多<i className="iconfont icon-right"/></Link> : ''
                        }
                        
                        </Caption>
                    }        
                    
                    
                    {bindCards.map((item,index) =>{
                        return <BankCard  card={item} key={index} accountStatus={this.state.accountStatus}/>
                    } )}
                    {
                        bindCards.length == 0 && this.state.accountStatus ==0 ? <div className="padding10">暂无银行卡</div> : ''
                    }
                    {
                        bindCards.length == 0 && this.state.accountStatus!=0 ? <div className="padding10">账户待审核，暂未绑定任何银行卡</div> : ''
                    }
                    
                    {/* 我的账单*/}
                    <div className={this.props.walletinfo.Ceiling ? 'Ceiling' : 'Ceiled'}>
                        <Caption title="我的账单" className="bill-group">
                        {
                            this.state.billBtnList && this.state.billBtnList.length>1 ? <BtnGroup BtnList = {this.state.billBtnList}  value={this.state.accType} onChange={this.accTypeChange.bind(this)}></BtnGroup> : ''
                        }
                        </Caption>
                    </div>
                    <BillList billList={this.state.billList} accountStatus={this.state.accountStatus} accType={this.state.accType}/>
                    {
                        this.state.billList && this.state.billList.length ? <LoadMore hasMore={this.state.billHasMore} loadMoreFn={this.handLoadMore.bind(this)}/> : ''
                    }
                    
                    </div>
                        {/*</PullLoad>       */}
                        </div>
                
            }
            </div>
)
}


}
// -------------------redux react 绑定--------------------

function mapStateToProps(state) {
    return {
        walletinfo: state.walletinfo
    }
}

function mapDispatchToProps(dispatch) {
    return {
        walletinfoActions: bindActionCreators(walletInfoActionsFromOtherFile, dispatch)
    }
}
export default connect(
    mapStateToProps,
    mapDispatchToProps
    )(MyWallet)
